package com.uls.czj.service.impl;

import java.util.*;

import com.uls.common.core.domain.entity.SysUser;
import com.uls.hdh.domain.HdhUsers;
import com.uls.hdh.mapper.HdhUsersMapper;
import com.uls.hdh.vo.TaskCommentVo;
import com.uls.system.service.ISysUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.czj.mapper.CzjHousingsubsidyMapper;
import com.uls.czj.domain.CzjHousingsubsidy;
import com.uls.czj.service.ICzjHousingsubsidyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 住房补贴管理Service业务层处理
 * 
 * @author czj
 * @date 2024-11-10
 */
@Service
public class CzjHousingsubsidyServiceImpl implements ICzjHousingsubsidyService 
{
    @Autowired
    private CzjHousingsubsidyMapper czjHousingsubsidyMapper;



    @Autowired
    private RuntimeService runtimeService;


    @Autowired
    private TaskService taskService;

    @Autowired
    private HdhUsersMapper hdhUsersMapper;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private HistoryService historyService;


    /**
     * 查询住房补贴管理
     * 
     * @param subsidyid 住房补贴管理主键
     * @return 住房补贴管理
     */
    @Override
    public CzjHousingsubsidy selectCzjHousingsubsidyBySubsidyid(Long subsidyid)
    {
        return czjHousingsubsidyMapper.selectCzjHousingsubsidyBySubsidyid(subsidyid);
    }

    /**
     * 查询住房补贴管理列表
     * 
     * @param czjHousingsubsidy 住房补贴管理
     * @return 住房补贴管理
     */
    @Override
    public List<CzjHousingsubsidy> selectCzjHousingsubsidyList(CzjHousingsubsidy czjHousingsubsidy)
    {
        return czjHousingsubsidyMapper.selectCzjHousingsubsidyList(czjHousingsubsidy);
    }

    /**
     * 新增住房补贴管理
     * 
     * @param czjHousingsubsidy 住房补贴管理
     * @return 结果
     */
    @Override
    public int insertCzjHousingsubsidy(CzjHousingsubsidy czjHousingsubsidy)
    {
        return czjHousingsubsidyMapper.insertCzjHousingsubsidy(czjHousingsubsidy);
    }

    /**
     * 修改住房补贴管理
     * 
     * @param czjHousingsubsidy 住房补贴管理
     * @return 结果
     */
    @Override
    public int updateCzjHousingsubsidy(CzjHousingsubsidy czjHousingsubsidy)
    {
        return czjHousingsubsidyMapper.updateCzjHousingsubsidy(czjHousingsubsidy);
    }

    /**
     * 批量删除住房补贴管理
     * 
     * @param subsidyids 需要删除的住房补贴管理主键
     * @return 结果
     */
    @Override
    public int deleteCzjHousingsubsidyBySubsidyids(Long[] subsidyids)
    {
        return czjHousingsubsidyMapper.deleteCzjHousingsubsidyBySubsidyids(subsidyids);
    }

    /**
     * 删除住房补贴管理信息
     * 
     * @param subsidyid 住房补贴管理主键
     * @return 结果
     */
    @Override
    public int deleteCzjHousingsubsidyBySubsidyid(Long subsidyid)
    {
        return czjHousingsubsidyMapper.deleteCzjHousingsubsidyBySubsidyid(subsidyid);
    }

    @Override
    @Transactional
    public int submit(Long subsidyid, Long userId) {
        CzjHousingsubsidy czjHousingsubsidy = czjHousingsubsidyMapper.selectCzjHousingsubsidyBySubsidyid(subsidyid);


        String processDefiKey = "czjWord";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 138);  //先写死，是主任的编号
        //没有启动这个流程
        if (czjHousingsubsidy.getSubsidystatus().equals("0")) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            czjHousingsubsidy.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));  // 把流程实例id与业务系统绑定
            czjHousingsubsidy.setSubsidystatus("2");//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee("" + userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());

            return czjHousingsubsidyMapper.updateCzjHousingsubsidy(czjHousingsubsidy);
        }
        //流程启动了，打回重新审批，就不用再启动流程
        else {
            Long flowInstantId = czjHousingsubsidy.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            czjHousingsubsidy.setSubsidystatus("2");//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return czjHousingsubsidyMapper.updateCzjHousingsubsidy(czjHousingsubsidy);
        }
    }

    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {
        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user=userService.selectUserById(Long.parseLong(com.getUserId()));  //查询用户名

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }

            taskCommentVoList.add(taskCommentVo);

        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();

        for(int i= taskCommentVoList.size()-1;i>=0;i--)
        {
            TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }

        return taskCommentVoListSort;
    }

    @Override
    public List<CzjHousingsubsidy> finishTask(Long userId, String processDefiniionKey, CzjHousingsubsidy czjHousingsubsidy) {
        List<CzjHousingsubsidy> listStudent=new ArrayList<CzjHousingsubsidy>();
        // 办理人的任务列表
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance task: list) {
                if (!task.getName().equals("学生请假申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    czjHousingsubsidy.setFlowInstantId(flowInstanceId);
                    //根据流程id和其他条件查询老师mapper的方法
                    CzjHousingsubsidy czjHousingsubsidy1 = czjHousingsubsidyMapper.selectStudentFlowIdOther(czjHousingsubsidy);

                    if (czjHousingsubsidy1!=null) {
                        HdhUsers hdhUsers = hdhUsersMapper.selectHdhUsersByUsersId(czjHousingsubsidy1.getPersonnelid());
                        czjHousingsubsidy1.setPersonnelname(hdhUsers.getUsername());
                        listStudent.add(czjHousingsubsidy1);
                    }
                }

            }
        }
        if (listStudent.size()==0){
            return listStudent;
        }
        List<CzjHousingsubsidy> list1 = new ArrayList<>(new HashSet<>(listStudent));
        return list1;
    }

    @Override
    public List<CzjHousingsubsidy> noFinishTask(Long userId, String myWorkProcess, CzjHousingsubsidy czjHousingsubsidy) {
        List<CzjHousingsubsidy> listStudent=new ArrayList<CzjHousingsubsidy>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(myWorkProcess)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("提交审批")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    czjHousingsubsidy.setFlowInstantId(flowInstanceId);
                    //根据流程id和其他条件查询老师mapper的方法
                    CzjHousingsubsidy czjHousingsubsidy1 = czjHousingsubsidyMapper.selectStudentFlowIdOther(czjHousingsubsidy);

                    HdhUsers hdhUsers = hdhUsersMapper.selectHdhUsersByUsersId(czjHousingsubsidy1.getPersonnelid());
                    czjHousingsubsidy1.setPersonnelname(hdhUsers.getUsername());
                    if (czjHousingsubsidy1!=null)
                        listStudent.add(czjHousingsubsidy1);
                }

            }
        }

        return listStudent;
    }

    @Override
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Long subsidyid) {
        CzjHousingsubsidy czjHousingsubsidy = czjHousingsubsidyMapper.selectCzjHousingsubsidyBySubsidyid(subsidyid);


        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();

        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("管理员审批")){
                    if (agree==1){
                        params.put("inputUser3", 121);  //固定一个人员4
                        czjHousingsubsidy.setSubsidystatus("2");//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    }else {
                        czjHousingsubsidy.setSubsidystatus("1");
                    }
                    params.put("pass1", agree);  //给流程变量赋值

                }else if (task.getName().equals("主任审批")){
                    if (agree==1){
                        params.put("inputUser4", 122);
                        czjHousingsubsidy.setSubsidystatus("2");
                    }
                    else {
                        czjHousingsubsidy.setSubsidystatus("1");
                    }
                    params.put("pass2", agree);  //给流程变量赋值
                }
                else if (task.getName().equals("院长审批")){
                    if (agree==1){
                        czjHousingsubsidy.setSubsidystatus("3");
                        czjHousingsubsidy.setIssuedate(new Date());
                    }
                    else {
                        czjHousingsubsidy.setSubsidystatus("1");
                    }
                    params.put("pass3", agree);  //给流程变量赋值
                }

                czjHousingsubsidyMapper.updateCzjHousingsubsidy(czjHousingsubsidy);

                // 添加批注时候的审核人，通常应该从session获取,现在从redis
                Authentication.setAuthenticatedUserId(userId.toString());
                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                // taskId：任务id
                taskService.complete(task.getId(), params);

            }
        }
    }




}
